package com.daxia.bumall.service;

import java.io.IOException;

import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.daxia.bumall.common.Logs;
import com.daxia.bumall.dao.CityDAO;
import com.daxia.bumall.dao.DistrictDAO;
import com.daxia.bumall.dto.DistrictDTO;
import com.daxia.bumall.dto.GPSAddressDTO;
import com.daxia.bumall.model.City;
import com.daxia.bumall.model.District;

@Service
public class LocationService {
	// doc http://lbsyun.baidu.com/index.php?title=webapi/ip-api
	
	private static String bd_ak = "XTGKLrQc478mYXsm3RnoA4HrwjZnI3WB";
	private static String bd_url = "http://api.map.baidu.com/location/ip";
	private static String byIPUrlTemplate = bd_url + "?ak=" + bd_ak + "&ip={ip}";
	private static String byGPSUrlTemplate = "http://api.map.baidu.com/geocoder/v2/?ak=" + bd_ak + "&location={lat},{lng}&output=json&pois=1";
	private static Logger logger = Logger.getLogger(LocationService.class);
	 @Autowired
    private DistrictDAO districtDAO;
    @Autowired
    private CityDAO cityDAO;
	
    public GPSAddressDTO getDefaultAddress() {   //默认的地址是东莞
    	String proName = "广东省";
    	String cityName = "东莞市"; 
    	String districtName = "厚街镇";
    	DistrictDTO districtDTO = new DistrictDTO();
        districtDTO.setName(districtName);
        districtDTO.setCity(new City());
        districtDTO.getCity().setName(cityName);
        District district = districtDAO.findOne(districtDTO);
        if (district != null) {
            GPSAddressDTO address = new GPSAddressDTO();
            address.setDistrict(district);
            address.setCity(district.getCity());
            address.setProvince(district.getCity().getProvince());
            return address;
        }

        City city = cityDAO.findByName(cityName);
        if (city != null) {
            GPSAddressDTO address = new GPSAddressDTO();
            address.setCity(city);
            address.setProvince(city.getProvince());
            return address;
        }
        return null;
    }
    
	public GPSAddressDTO getGPSAddressByIP(String ip) {
		try {
			String url = byIPUrlTemplate.replace("{ip}", ip);
			String text = Jsoup.connect(url).ignoreContentType(true).get().text();
			JSONObject json = JSONObject.parseObject(text);
			Integer status = json.getInteger("status");
			if (status != 0) { // 失败
				Logs.COMMON.debug("locate ip failed, ip: " + ip + ", message: " + json.getString("message"));
				return null;
			} else {
				JSONObject detailObj = json.getJSONObject("content").getJSONObject("address_detail");
				String districtName = detailObj.getString("district");
		        String cityName = detailObj.getString("city");
		        
		        if (logger.isDebugEnabled()) {
		            logger.debug("districtName: " + districtName + ", cityName: " + cityName);
		        }
		        
		       /* DistrictDTO districtDTO = new DistrictDTO();
		        districtDTO.setName(districtName);
		        districtDTO.setCity(new City());
		        districtDTO.getCity().setName(cityName);
		        District district = districtDAO.findOne(districtDTO);
		        if (district != null) {
		            GPSAddressDTO address = new GPSAddressDTO();
		            address.setDistrict(district);
		            address.setCity(district.getCity());
		            address.setProvince(district.getCity().getProvince());
		            return address;
		        }*/
		        City city = cityDAO.findByName(cityName);
		        if (city != null) {
		            GPSAddressDTO address = new GPSAddressDTO();
		            address.setCity(city);
		            address.setProvince(city.getProvince());
		            return address;
		        }
			}
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		return null;
	}
	
	public String getAddressByIP(String ip) {
		try {
			String url = byIPUrlTemplate.replace("{ip}", ip);
			String text = Jsoup.connect(url).ignoreContentType(true).get().text();
			JSONObject json = JSONObject.parseObject(text);
			Integer status = json.getInteger("status");
			if (status != 0) { // 失败
				Logs.COMMON.debug("locate ip failed, ip: " + ip + ", message: " + json.getString("message"));
			}
			String address = json.getJSONObject("content").getString("address");
			return address;
		} catch (IOException e) {
			e.printStackTrace();
			return "";
		}
	}
	
	public static void main(String[] args) {
		Logs.COMMON.debug(new LocationService().getAddressByIP("61.145.210.27"));
		Logs.COMMON.debug(new LocationService().getGPSAddressByIP("61.145.210.27").getCity().getName());
		//Logs.COMMON.debug(new LocationService().getAddresByGPS(38.85788953, 115.47866821));
	}
	
	public String getAddresByGPS(double lat, double lng) {
		try {
			String url = byGPSUrlTemplate.replace("{lat}", lat + "").replace("{lng}", lng + "");
			String text = Jsoup.connect(url).ignoreContentType(true).get().text();
			JSONObject json = JSONObject.parseObject(text);
			Logs.COMMON.debug(json);
			Integer status = json.getInteger("status");
			if (status != 0) { // 失败
				Logs.COMMON.debug("locate by gps failed, lat: " + lat + ", lng: " + lng + ", message: " + json.getString("message"));
			}
			String address = json.getJSONObject("result").getString("formatted_address");
			return address;
		} catch (IOException e) {
			e.printStackTrace();
			return "";
		}
	}
	
}
